//引入gulp
const gulp = require('gulp')

//引入cssmin
const cssmin = require('gulp-cssmin')

//引入scss和gulpscss
const sass = require('gulp-sass')(require('sass'))

//引入gulp-uglify，压缩js
const uglify = require('gulp-uglify')

//引入'gulp-babel' es6转es5
const bable = require('gulp-babel')

//引入webserver
const webserver = require('gulp-webserver')

//引入gulb-htmlmin 压缩html
const htmlmin = require('gulp-htmlmin')

//引入gulp-clean
const clean = require('gulp-clean')

//打包css
gulp.task('css', function () {
    return gulp.src('./src/css/**')
        .pipe(cssmin())
    .pipe(gulp.dest('./dist/css'))
})

//打包scss
gulp.task('scss', function () {
    return gulp
        .src('./src/scss/**')
        .pipe(sass())
        .pipe(cssmin())
    .pipe(gulp.dest('./dist/css'))
})

//打包js文件 压缩  js5转js6
gulp.task('js', function () {
    return gulp.src('./src/js/**')
        .pipe(bable({
            presets:['es2015']
        }))
        .pipe(uglify())
    .pipe(gulp.dest('./dist/js'))
})

//打包html文件 压缩处理
gulp.task('pages', function () {
    return gulp.src('./src/pages/**')
        .pipe(htmlmin({
            removeEmptyAttributes: true,
            collapseWhitespace:true
        }))
    .pipe(gulp.dest('./dist/pages'))
})

//打包static和lib
gulp.task("static", function () {
    return gulp.src('./src/static/**')
    .pipe(gulp.dest('./dist/static'))
})
gulp.task("lib", function () {
    return gulp.src('./src/lib/**')
    .pipe(gulp.dest('./dist/lib'))
})

//清除dist目录
gulp.task('clean', function () {
    return gulp.src('./dist',{allowEmpty:true})
    .pipe(clean())
})

/* webserver任务 */
gulp.task('webserver',function(){
    return gulp.src('./dist')
            .pipe(webserver({
                host:'localhost',
                port:3000,
                livereload:true,
                open:'./pages/login.html'
            }))
})


/* 侦听任务 */
gulp.task('watch',function(){
    gulp.watch('./src/css/**', gulp.series('css'))
    gulp.watch('./src/js/**', gulp.series('js'))
    gulp.watch('./src/scss/**', gulp.series('scss'))
    gulp.watch('./src/pages/**', gulp.series('pages'))
    gulp.watch('./src/static/**', gulp.series('static'))
    gulp.watch('./src/lib/**', gulp.series('lib'))
})

//按顺序批量执行
gulp.task("task1", gulp.series('css', 'scss', 'js', 'pages', 'static', 'lib'))

//定义默认任务 直接通过gulp执行
exports.default = gulp.series('clean',
    gulp.parallel('css', 'scss', 'js', 'pages', 'static', 'lib'),
    'webserver','watch')

